package com.qiaoyanqing.textdemoqyq7.AsyncTasks;

import android.os.AsyncTask;
import android.util.Log;

import com.qiaoyanqing.textdemoqyq7.Beans.ViewpagerBean;
import com.qiaoyanqing.textdemoqyq7.CallBacks.ViewPagerCB;
import com.qiaoyanqing.textdemoqyq7.Utils.MyHttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/15.
 */

public class VPAsyncTask extends AsyncTask<String ,Void,List<ViewpagerBean>>{
    private List<ViewpagerBean>mData=new ArrayList<>();
    private ViewPagerCB mViewPagerCB;

    public VPAsyncTask(ViewPagerCB viewPagerCB) {
        mViewPagerCB = viewPagerCB;
    }

    @Override
    protected List<ViewpagerBean> doInBackground(String... strings) {
        String result= MyHttpUtils.getStringFromUrl(strings[0]);
        List<ViewpagerBean>list=parseJson(result);
        return list;
    }

    private List<ViewpagerBean> parseJson(String result) {

        try {
            JSONObject jsonObject=new JSONObject(result);
            JSONArray jsonArray=jsonObject.optJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1=jsonArray.optJSONObject(i);
                ViewpagerBean viewpagerBean=new ViewpagerBean();
                viewpagerBean.setImage(jsonObject1.optString("image"));
                viewpagerBean.setTitle(jsonObject1.optString("title"));
                mData.add(viewpagerBean);
            }
            Log.d("flag", " Viewpager parseJson: "+mData.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mData;
    }

    @Override
    protected void onPostExecute(List<ViewpagerBean> viewpagerBeen) {
        super.onPostExecute(viewpagerBeen);
        if (viewpagerBeen != null) {
            mViewPagerCB.sendData(viewpagerBeen);
        }
    }
}
